package com.pay.sdk.usage;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pay.sdk.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;


public class GoodsListActivity extends Activity implements View.OnClickListener {

    private GoodsListAdapter listAdapter;
    private ListView listView;
    private ArrayList<GoodsInfoModel> arrayList = new ArrayList<GoodsInfoModel>();
    private Button mSubStepPayBtn, mStepPayBtn;
    private static final String PRICE = "5";
    private int mPosition = 0;
    protected Dialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_list_acitvity);
        initViews();
        initData();
    }

    private void initViews() {
        listView = (ListView) findViewById(R.id.GoodsListAcitvity_GoodsList);
        mSubStepPayBtn = (Button) findViewById(R.id.substep_pay_btn);
        mStepPayBtn = (Button) findViewById(R.id.step_pay_btn);
        mSubStepPayBtn.setOnClickListener(this);
        mStepPayBtn.setOnClickListener(this);
    }

    private void initData() {
        for (int i = 0; i < 1; i++) {
            GoodsInfoModel goodsInfoModel = new GoodsInfoModel();
            goodsInfoModel.setGoodsName(getString(R.string.goods_name));
            goodsInfoModel.setGoodsPrice(PRICE);
            arrayList.add(goodsInfoModel);
        }
        listAdapter = new GoodsListAdapter(this, arrayList);
        listView.setAdapter(listAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPosition = position;
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                TextView textView = (TextView) view.findViewById(R.id.item_TextView_GoodsList_Price);
                showInputDialog(position, textView);
                return true;
            }
        });
    }

    private void showInputDialog(final int position, final TextView textView) {
        /*@setView add EditView  */
        final EditText editText = new EditText(GoodsListActivity.this);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editText.setText(textView.getText().toString());
        editText.addTextChangedListener(new SearchWather(editText));
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(GoodsListActivity.this);
        inputDialog.setTitle(R.string.please_input_price).setView(editText);
        inputDialog.setPositiveButton(R.string.confirm,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (!TextUtils.isEmpty(editText.getText().toString())) {
                                DecimalFormat df = new DecimalFormat("0.00");
                                String price = df.format(Double.parseDouble(editText.getText().toString()));
                                textView.setText(price);
                                arrayList.get(position).setGoodsPrice(price);
                            } else {
                                Toast.makeText(GoodsListActivity.this, R.string.data_cannot_empty, Toast.LENGTH_SHORT).show();
                            }
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                            textView.setText(PRICE);
                            Toast.makeText(GoodsListActivity.this, R.string.data_format_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                }).show();
    }

    /**
     * edittext Filter only number and .
     */
    private String stringFilterText(String str) throws PatternSyntaxException {
        String regEx = "[^0-9.]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    @Override
    public void onClick(final View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.substep_pay_btn:
                intent = new Intent(GoodsListActivity.this, PayActivity.class);
                break;
            case R.id.step_pay_btn:
                intent = new Intent(GoodsListActivity.this, SingleStepPayActivity.class);
                break;
            default:
                break;
        }
        intent.putExtra("GoodsName", arrayList.get(mPosition).getGoodsName());
        intent.putExtra("GoodsPrice", arrayList.get(mPosition).getGoodsPrice());
        intent.putExtra("position", mPosition);
        startActivity(intent);
    }

    private void dismiss() {
        if (null != mProgressDialog && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    /**
     * Text input box special character filtering
     */
    private class SearchWather implements TextWatcher {
        //Listen to changes the text box
        private EditText editText;

        SearchWather(EditText editText) {
            this.editText = editText;
        }

        @Override
        public void onTextChanged(CharSequence ss, int start, int before, int count) {
            String editable = editText.getText().toString();
            String str = stringFilterText(editable);
            if (str.contains(".")) {
                String strDecimal = str.substring(str.indexOf("."));
                if (strDecimal.length() > 3) {
                    str = str.substring(0, str.indexOf(".") + 3);
                }
            }
            if (!editable.equals(str)) {
                editText.setText(str);
                //new selection position
                editText.setSelection(str.length());
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
    }
}
